var TeacherCourse = function () {

    var event = function () {
        //1.初始化周列表
        // var cb = $.Callbacks();
        // cb.add(initWeek);
        // cb.add(initTable);
         initWeek($("#year").val());
        // cb.fire($("#year").val());
        // cb.fire();


        //年切换的事件
        $("#year").change(function () {
            var changeYear = $("#year").val();
            initWeek(changeYear);
        });
        $("#week").change(function () {
           initTable();
        });

        //本周
        $("#btn_current_week").click(function () {
            var today = new Date();
            var year = today.getFullYear();
            $("#year option[value='" + year + "']").attr("selected", true);
            initWeek(year);
        });

        //下周
        $("#btn_next_week").click(function () {

            $("#week").find("option:selected").next().attr("selected", true);

        });

        //周一至周日事件
        $("#chkbox_week input[type='checkbox']").click(function () {
            var index=$(this).val();
            // var index=parseInt(no);
            // alert($(this).is(':checked'));
            // $('#table tr').find('th:eq(13)').hide();
            if ($(this).is(':checked')){
                $('#course_table3 tr').find('th:eq('+index+')').show();
                $('#course_table3 tr').find('td:eq('+index+')').show();
            }else {
                $('#course_table3 tr').find('th:eq('+index+')').hide();
                $('#course_table3 tr').find('td:eq('+index+')').hide();
            }


        });

        // 1.删除
        $("#course_table").on("click", "td a.course_delete", function () {
            var roleId = $(this).attr("data-id");
            layer.confirm('您确定要删除吗，删除后不可恢复？', {
                title: '删除课程',
                btn: ['是', '否'],
                btnAlign: 'c'
                // 按钮
            }, function () {

            }, function () {
            });
        });
        // 2.编辑
        $("#course_table").on(
            "click",
            "td a.course_edit",
            function () {
                var roleId = $(this).attr("data-id");
                layer.open({
                    title: '编辑课程',
                    btn: ['是', '否'],
                    type: 2,
                    // skin: 'layui-layer-rim', //加上边框
                    // area: ['620px', 'auto'], //宽高
                    area: ["60%", "40%"],
                    content: "/course/" + roleId,
                    yes: function (index, layerno) {
                        var body = layer.getChildFrame('body', index);

                        var $courseName = body.find("#course_name");
                        var $form = body.find("#course_edit_form");

                        if (!$courseName.val()) {
                            layer.msg("亲，课程系列名称不能为空！", {
                                icon: 2
                            });
                            return;
                        }
                        var form_data = $form.serializeArray();
                        var post_data = {};
                        $.map(form_data, function (n, i) {

                            var key = n['name'];
                            var value = n['value'];
                            if (key && post_data.hasOwnProperty(key)) {
                                let originValue = post_data[key];
                                let newValue = originValue + "," + value;
                                post_data[key] = newValue;
                            } else {
                                post_data[key] = value;
                            }

                        });
                        submitForm(JSON.stringify(post_data), "PUT", "/course/" + roleId);
                    },
                    btn2: function (index, layerno) {
                    }
                });

            });

        // 3.添加
        $("#btn_course_add").click(function () {

            var course_name = $("#course_name").val();
            if (!course_name) {
                layer.msg("亲，课程名称不能为空！", {
                    icon: 2
                });
                return;
            }
            var form_data = $("#course_form").serializeArray();
            var post_data = {};
            $.map(form_data, function (n, i) {

                var key = n['name'];
                var value = n['value'];
                if (key && post_data.hasOwnProperty(key)) {
                    let originValue = post_data[key];
                    let newValue = originValue + "," + value;
                    post_data[key] = newValue;
                } else {
                    post_data[key] = value;
                }

            });
            submitForm(JSON.stringify(post_data), "POST", "/course");
            //触发reset按钮，清空表单
            $("input[type=reset]").trigger("click");
        });
    };

    function initWeek(year, checkIndex) {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/week?year=" + year,
        }).done(function (data) {
            if (data && data.retCode == 1) {
                var weeks = data.retObj;
                var option = '';
                $.each(weeks, function (index, week) {
                    if (week.currentWeek) {
                        option += '<option selected value="' + week.week + '" data-startDate="' + week.startDate + '" data-endDate="' + week.endDate + '">第' + week.week + '周[' + week.startDate + '~' + week.endDate + ']</option>';
                    } else {
                        option += '<option value="' + week.week + '" data-startDate="' + week.startDate + '" data-endDate="' + week.endDate + '">第' + week.week + '周[' + week.startDate + '~' + week.endDate + ']</option>';
                    }

                });
                $("#week").html("");
                $("#week").html(option);

                // initTable();

            }

        }).done(function () {
            initTable();

        }).fail(function (d) {
            layer.msg("服务器无响应", {
                icon: 2
            });

        });
    }
    function addDate(date, days) {
        if (days == undefined || days == '') {
            days = 1;
        }
        var date = new Date(date);
        date.setDate(date.getDate() + days);
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
    }

    // 日期月份/天的显示，如果是1位数，则在前面加上'0'
    function getFormatDate(arg) {
        if (arg == undefined || arg == '') {
            return '';
        }

        var re = arg + '';
        if (re.length < 2) {
            re = '0' + re;
        }

        return re;
    }
    function initTable() {
        var WEEK=["星期一","星期二","星期三","星期四","星期五","星期六","星期日"];
        var $week = $("#week");
        var week = $week.val();
        var start = $week.find("option:selected").attr("data-startDate");
        var title = '<th>第' + week + '周 课程表</th>';
        let startDate = new Date(start);
        for (let j = 0; j < 7; j++) {

            title += '<th>' + WEEK[j] + '(' + (startDate.getMonth()+1)+'.' +startDate.getDate()+ ')</th>';
            startDate.setDate(startDate.getDate()+1);
        }
        $("#tbl_course_title").html("");
        $("#tbl_course_title").html(title);
        renderDataToTable();

    }


    /**
     * 获取老师的排班数据
     *
     * @param data
     */
    function renderDataToTable() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/teacher_course",
            contentType: "application/json;charset=utf-8",
            data: "startDate=2017-11-13"
        }).done(function (data) {
            if (data && data.retCode == 1) {
                var retObj=data.retObj;
                var tbody='';
                var time=retObj.time;
                var course=retObj.course;

                $.each(time,function (index,t) {
                    let startDate = new Date("2017-11-13");
                    let cTimes=t.courseTime.split(",");
                    let showtime=cTimes[0]+":"+cTimes[1]+"-"+cTimes[2]+":"+cTimes[3];
                    let tr='<tr>';
                    let td='<td>'+showtime+'</td>';
                    let trCourse=course[t.id];


                    for(let i=0;i<7;i++){
                        let timeKey=startDate.getFullYear()+'-'+(startDate.getMonth()+1)+'-'+startDate.getDate();
                        let tdCourse=trCourse[timeKey];
                        if(tdCourse){
                            td+='<td>'+tdCourse.className+'</td>';
                        }else{
                            td+='<td>'+i+'</td>';
                        }
                        startDate.setDate(startDate.getDate()+1);
                    }

                    tr+=tr+td+'</tr>';
                    tbody+=tr;
                });

                $("#tbl_course_body").html("");
                $("#tbl_course_body").html(tbody);
            }

        }).fail(function (d) {
            layer.msg("服务器无响应");

        });
    }

    return {
        init: function () {

            event();
        }
    };

}();